<?php
/* explain:		news system
 * Project:     
 * File:        news.php
 *
 * @ link 		http://www.../modules/
 * @ Email		ldmmyx@hotmail.com
 * @ copyright 	2005  Ling Deming
 * @ author 	ivan.ling  Ling Deming
 * @ version 	1.0
 *
 */
include_once("Common.php");
include_once("domain/CategoryDomain.php");
include_once("dao/CommonDAO.php");
include_once("dao/CategoryDAO.php");
class CategoryImpl extends Common implements CategoryDAO, CommonDAO
{
	private $conn;
	private $message;
	private $DBTag;

	function CategoryImpl($DBTag)
	{
		parent::Common();
		
		$this->DBTag	= $DBTag;
		$this->conn 	= $this->getConnection($DBTag);
		
	}

	/* get data via ID
	 *
	 * @param  int    id
	 * @return mixed  false:
	 */
	public function getById($id)
	{
		$sql  = 'SELECT id, parentId, name, title, descript, r_couponCount ';
		$sql .= "FROM category WHERE id = $id";
		
		try {
			$rs = mysql_query($sql, $this->conn);
			if ($rs && $row = mysql_fetch_row($rs)) {
				$oCategoryDomain = new CategoryDomain();

				$oCategoryDomain->setId($row[0]);
				$oCategoryDomain->setParentId($row[1]);
				$oCategoryDomain->setName($row[2]);
				$oCategoryDomain->setTitle($row[3]);
				$oCategoryDomain->setDescript($row[4]);
				$oCategoryDomain->setCouponCount($row[5]);
						
				return $oCategoryDomain;
			} else {
				$this->messages = "get coupon data failed by Id. sql : $sql <br>";
				$this->messages .= "error: " . mysql_error($this->conn);

				return null;
			}
		} catch (Exception $e) {
			$this->messages = $e->getMessage();

			return null;
		}
	}

/* get data via ID
	 *
	 * @param  int    id
	 * @return mixed  false:
	 */
	public function getByName($name)
	{
		$sql  = 'SELECT id, parentId, name, title, descript, r_couponCount ';
		$sql .= "FROM category WHERE name = '$name'";
		
		try {
			$rs = mysql_query($sql, $this->conn);
			if ($rs && $row = mysql_fetch_row($rs)) {
				$oCategoryDomain = new CategoryDomain();

				$oCategoryDomain->setId($row[0]);
				$oCategoryDomain->setParentId($row[1]);
				$oCategoryDomain->setName($row[2]);
				$oCategoryDomain->setTitle($row[3]);
				$oCategoryDomain->setDescript($row[4]);
				$oCategoryDomain->setCouponCount($row[5]);
						
				return $oCategoryDomain;
			} else {
				$this->messages = "get coupon data failed by Id. sql : $sql <br>";
				$this->messages .= "error: " . mysql_error($this->conn);

				return null;
			}
		} catch (Exception $e) {
			$this->messages = $e->getMessage();

			return null;
		}
	}

	public function getByCouponId($couponId)
	{
		$sql  = 'SELECT c.id, c.parentId, c.name, c.title, c.descript, c.r_couponCount ';
		$sql .= "FROM category c, coupon_category cc WHERE c.id = cc.categoryId AND cc.couponId = $couponId LIMIT 1";
		
		try {
			$rs = mysql_query($sql, $this->conn);
			if ($rs && $row = mysql_fetch_row($rs)) {
				$oCategoryDomain = new CategoryDomain();

				$oCategoryDomain->setId($row[0]);
				$oCategoryDomain->setParentId($row[1]);
				$oCategoryDomain->setName($row[2]);
				$oCategoryDomain->setTitle($row[3]);
				$oCategoryDomain->setDescript($row[4]);
				$oCategoryDomain->setCouponCount($row[5]);
						
				return $oCategoryDomain;
			} else {
				$this->messages = "get coupon data failed by Id. sql : $sql <br>";
				$this->messages .= "error: " . mysql_error($this->conn);

				return null;
			}
		} catch (Exception $e) {
			$this->messages = $e->getMessage();

			return null;
		}
	}
	
	public function add($oCategoryDomain)
	{
		
		if($oCategoryDomain instanceof CategoryDomain){
			$IDkey = md5($oCategoryDomain->getMerchantId() . $oCategoryDomain->getCode() . $oCategoryDomain->getAmount() . $oCategoryDomain->getDescript());
			
			$sql 	 = "INSERT INTO category SET parentId";
			$sql	.= $oCategoryDomain->getParentId();
			
			$sql 	.= ", name='";
			$sql	.= addslashes($oCategoryDomain->getName());
	
			$sql 	.= "', title='";
			$sql	.= addslashes($oCategoryDomain->getTitle());
	
			$sql 	.= "', descript='";
			$sql	.= addslashes($oCategoryDomain->getDescript());

			$sql	.= "', status=";
			$sql	.= $oCategoryDomain->getStatus();
			
			$id		= 0;
			
			try{
				$rs  	= mysql_query($sql, $this->conn);
				if($rs){
					$id = mysql_insert_id($this->conn);
					
					$oAttribute->setId($id);
					
					$this->messages = "add successfully. id = $id";
				}else{
					$this->messages  = "add failed. sql : $sql . <br>";
					$this->messages .= "error: " .  mysql_error($this->conn);
				}
			}catch(Exception $e){
				$this->messages = $e->getMessage();
				
				$id	= -1;
			}
		}else{
			$id	= -1;
			
			$this->message = 'input object is not instance of CategoryDomain.';
		}
			
		return $id;
	}
	
	/* edit
	 *
	 * @param  string 	userid		news class name 
	 * @param  string 	number		man number  
	 * @param  string  	position    position
	 * @param  string 	summary		summary 
	 * @param  string 	descript	descript  
	 * @param  datetime	startDate	start date
	 * @param  datetime endDate		end date
 	 	 * @param  return 	boolean
	 */
	public function edit($oCategoryDomain)
	{
		$merchantId = $oCategoryDomain->getMerchantId();
		$code		= $oCategoryDomain->getCode();
		$amount		= $oCategoryDomain->getAmount();
		$descript	= $oCategoryDomain->getDescript();
		
		$IDkey = md5($merchantId . $code . $amount . $descript);
		
		$sql = "UPDATE category SET merchantID='$merchantId', categoryID='$categoryID', code = '$code', descript = '$descript', URL = '$URL', expireDate = '$expireDate', " .
				"startDate = '$startDate', startPrice = '$startPrice', longRestr = '$longRestr', amount = '$amount', isFeatured = '$isFeatured', " .
				"isFreeShipping = '$isFreeShipping', isFreeGift = '$isFreeGift', isFreeSample = '$isFreeSample', isClearanceSales = '$isClearanceSales', " .
				"status = '$status', comments = '$comments', IDkey = '$IDkey', createdTime = UTC_TIMESTAMP() WHERE id = $id";
		$rs	 = mysql_query($sql, $this->conn) or die (mysql_error($this->conn));
		if($rs)
			return true;
		else
			return false;
	}
	
	/* delete news class
	 *
	 * @param  int    	id
	 * @param  string  	status
	 * @param  return 	boolean
	 */
	public function delete($id)
	{
		$sql = "DELETE FROM coupon WHERE id = $id";
		
		$rs	 = mysql_query($sql, $this->conn) or die (mysql_error());
		if($rs)
			return true;
		else
			return false;
	}
	
	public function getCatogories($page = 0, $discount = 20)
	{
		return $this->getCustoms(" WHERE status = 1 AND parentId = 0 AND r_couponCount > 0", " order by r_order", $page, $discount);
	}
	
	/* list
	 *
	 * @ param  string 	class id
	 * @ param  string 	page
	 * @ param  string 	discount
	 * @ param  string 	url
	 * @ param  return 	array
	 */
	public function getCustoms($where, $order, $page = 0, $discount = 20)
	{
		$arrback = array();
		
		try{
			$sql = "SELECT count(1) FROM category $where";
	
			$rs  = mysql_query($sql, $this->conn);
			
			list($total) = mysql_fetch_row($rs);
			
			$this->mutilPager($total, $page, $discount);
			
			if(!empty($total)){
				$sql  = 'SELECT id, parentId, name, title, descript, r_couponCount';
				$sql .= " FROM category  $where $order";
				$sql .= " LIMIT $this->firstcount, $discount";
				
				$rs  = mysql_query($sql, $this->conn);
				if($rs){
					while($row = mysql_fetch_array($rs)){
						$oCategoryDomain = new CategoryDomain();

						$oCategoryDomain->setId($row[0]);
						$oCategoryDomain->setParentId($row[1]);
						$oCategoryDomain->setName($row[2]);
						$oCategoryDomain->setTitle($row[3]);
						$oCategoryDomain->setDescript($row[4]);
						$oCategoryDomain->setCouponCount($row[5]);
						
						$arrback[] = $oCategoryDomain;
					}
				}else {
					$this->message = "select failed. sql : $sql";
					$this->message .= "<br>error: " . mysql_error($this->conn);

				}
			}
		}catch(Exception $e){
			$this->message = $e->getMessage();
			
			return null;
		}
		
		return $arrback;
	}
	
	public function getTopTree($categoryId)
	{	
		$topCatId = $this->getTopDirId($categoryId);
		
		return $this->getCategoryTree($topCatId);
	}
	
	public function getTopDirId($categoryId)
	{
		if($categoryId < 1)
			return $categoryId;
		
		while(true){
			$oCat = $this->getById($categoryId);
			if(is_object($oCat)){
				if($oCat->getParentId() > 0)
					$categoryId = $oCat->getParentId();
				else
					break;
			}else
				break;
		}
		
		return $categoryId;
	}
	
	public function getCategoryTree($categoryId)
	{
		if($categoryId < 1)
			return false;
		
		
		$arrTmpStack 	= array();
		$arrLevelStack 	= array();
		
		$i = 1;
		
		$oTopCat = $this->getById($categoryId);

		array_push($arrTmpStack, $oTopCat);
		array_push($arrLevelStack, $i);
		
		while(sizeof($arrTmpStack) > 0){
			$oCat 	= array_pop($arrTmpStack);
			$i 		= array_pop($arrLevelStack);
			
			$oCat->setLevel($i);
			
			$arrSubCategories = $this->getCustoms(" WHERE r_couponCount > 0 AND parentid=" . $oCat->getId(), ' ORDER BY name', 0, 1000);
			
			$i++;
			foreach($arrSubCategories as $subCategory){
				array_push($arrTmpStack, $subCategory);
				array_push($arrLevelStack, $i);
				
				$oCat->addSubCategory($subCategory);
			}
		}
		
		
		return $oTopCat;
	}
	
	public function getCategoryCouponCount($categoryId)
	{
		if($categoryId < 1)
			return 0;
		
		$couponCount	= 0;
		
		$arrTmpStack 	= array();
		$arrLevelStack 	= array();
		
		$i = 1;
		
		$oTopCat = $this->getById($categoryId);
		$couponCount = $oTopCat->getCouponCount();

		array_push($arrTmpStack, $oTopCat);
		array_push($arrLevelStack, $i);
		
		while(sizeof($arrTmpStack) > 0){
			$oCat 	= array_pop($arrTmpStack);
			$i 		= array_pop($arrLevelStack);
			
			$oCat->setLevel($i);
			
			$arrSubCategories = $this->getCustoms(" WHERE r_couponCount > 0 AND parentid=" . $oCat->getId(), '', 0, 1000);
			
			$i++;
			foreach($arrSubCategories as $subCategory){
				array_push($arrTmpStack, $subCategory);
				array_push($arrLevelStack, $i);
				
				$oCat->addSubCategory($subCategory);
				$couponCount += $subCategory->getCouponCount();
			}
		}
		
		
		return $couponCount;
	}
	
//	public function getSubDirs($parentid)
//	{
//		$arrParentid 	= array();
//		$arrTmpStack 	= array();
//		$arrLevelStack 	= array();
//		$arrClassid		= array();
//		
//		$i = 0;
//		array_push($arrTmpStack, $parentid);
//		
//		while(sizeof($arrTmpStack) > 0){
//			$strtmp = array_pop($arrTmpStack);
//			$i = array_pop($arrLevelStack);
//			if($strtmp > 0){
//				$oCat = $this->getById($strtmp);
//				if(is_object($oCat)){
//					$arrClassid[] = $oCat;
//					
////					$tmp = '';
////					for($j = 0; $j < $i; $j++){
////						$tmp.='&nbsp;&nbsp;&nbsp;&nbsp;';
////					}
////					$arrClassid[$strtmp] = $tmp . $oCat->getName();
//				}
//			}
//		
//			$sql = "SELECT id FROM category WHERE parentid=$strtmp";
//			
//	        $rs  = mysql_query($sql, $this->conn);
//			if($rs){
//				$mixBack = array();
//				
//				while($arrCache = mysql_fetch_array($rs)){
//					$mixBack[] = $arrCache;
//				}
//				
//				
//				if(is_array($mixBack)){
//					$i++;
//					foreach($mixBack as $value){
//						array_push($arrTmpStack, $value['id']);
//						array_push($arrLevelStack, $i);
//					}
//				}
//			}
//		}
//		
//		return $arrClassid;
//	}
	
	public function getLeafIds($parentid, $isIncludeParent = false)
	{
		$arrParentid 	= array();
		$arrTmpStack 	= array();
		$arrLevelStack 	= array();
		$arrClassid		= array();
		
		$i = 0;
		array_push($arrTmpStack, $parentid);
		
		while(sizeof($arrTmpStack) > 0){
			$strtmp = array_pop($arrTmpStack);
			$i 		= array_pop($arrLevelStack);
			if($strtmp > 0){
				$sql = "SELECT isLeaf FROM category WHERE id = $strtmp";
				
				$rs  = mysql_query($sql, $this->conn);
				if($rs){
					$arrback = mysql_fetch_array($rs);
					
					if($arrback['isLeaf'] == 1 && ($isIncludeParent && $strtmp == $parentid || $strtmp != $parentid))
						array_push($arrClassid, $strtmp);
				}
			}
		
		
			$sql = "SELECT id FROM category WHERE parentid=$strtmp";
			
	        $rs  = mysql_query($sql, $this->conn);
			if($rs){
				$mixBack = array();
				
				while($arrCache = mysql_fetch_array($rs)){
					$mixBack[] = $arrCache;
				}
				
				$i++;
				foreach($mixBack as $value){
					array_push($arrTmpStack,$value['id']);
					array_push($arrLevelStack,$i);
				}
			}
		}
		
		return $arrClassid;
	}
	
	public function getLeafIdsStr($parentid, $isIncludeParent = false, $glue = ',')
	{
		$arrLeafIds = $this->getLeafIds($parentid, $isIncludeParent);
		
		return implode($glue, $arrLeafIds);
	}
	
	public function getCouponCount()
	{
		$sql  = 'SELECT ct.categoryId, COUNT(1) FROM coupon c, coupon_category ct WHERE ct.couponId = c.id AND c.status = 1 GROUP BY ct.categoryId';
			
		return $this->getHash($this->DBTag, $sql);
	}
	
	public function getHasCoupons()
	{
		$sql  = 'SELECT id, r_couponCount FROM category WHERE status = 1 AND r_couponCount > 0';
			
		return $this->getHash($this->DBTag, $sql);
	}
	
	
	public function getCategoryIdByAlias($alias)
	{
		$sql  = "SELECT categoryId FROM category_alias WHERE alias = '" . addslashes($alias) . "'";
			
		return $this->getColumn($this->DBTag, $sql);
	}
	
	public function getCategoryByAlias($alias)
	{
		$categoryId = $this->getCategoryIdByAlias($alias);
			
		if(!empty($categoryId)){
			return $this->getById($categoryId);
		}else{
			return false;
		}
	}
	
	public function getMessage() 
	{
		return $this->message;
	}

	
	
}
?>
